import axios from 'axios'
// import { MessageBox, Message } from 'element-ui'
import store from '@/store'
// import { getToken } from '@/utils/auth'
// 引入路由
import router from '@/router'
// 设置基地址
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // baseURL: 'http://ihrm-java.itheima.net',
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    const token = store.state.user.token
    // 如果当前存有token,就加在请求头上
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  }
  , error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(response => {
  if (response.data.success) {
    // 操作成功
    return response.data
  } else {
    // 如果success为false 业务出错,直接触发reject
    // 被catch分支捕获
    return Promise.reject(new Error('请求错误'))
  }
}, error => {
  return Promise.reject(error)
})
async error => {
  console.log('请求出错啦', error)
  if (error.response.data.code === 10002) {
    console.log('token失效')
    await store.dispatch('user/logout')
    // .vue -- this.$route.fullPath
    //  .js -- router.currentRoute.fullPath

    router.push('/login?return_url=' + encodeURIComponent(router.currentRoute.fullPath))
  }
  console.dir(error)
  return Promise.reject(error)
}

export default service
